<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card style="margin-top: 15px">
      <el-button type="primary" @click="showAddRolesDialog">添加角色</el-button>
      <el-table border stripe :data="rolesList" style="margin-top: 15px">
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              v-for="(item, i) in scope.row.children"
              :key="item.id"
              :class="['bdbottom', i === 0 ? 'bdtop' : '', 'vcenter']"
            >
              <!-- 一级菜单 -->
              <el-col :span="4">
                <el-tag closable @close="removeId(scope.row, item.id)">{{
                  item.authName
                }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="20">
                <el-row
                  v-for="(item1, i1) in item.children"
                  :key="item1.id"
                  :class="[i1 === 0 ? '' : 'bdtop', 'vcenter']"
                >
                  <!-- 二级菜单 -->
                  <el-col :span="6">
                    <el-row>
                      <el-tag closable @close="removeId(scope.row, item1.id)">{{
                        item1.authName
                      }}</el-tag>
                      <i class="el-icon-caret-right"></i>
                    </el-row>
                  </el-col>
                  <!-- 三级菜单 -->
                  <el-col :span="18" style="text-align: left">
                    <el-tag
                      v-for="item2 in item1.children"
                      :key="item2.id"
                      closable
                      @close="removeId(scope.row, item2.id)"
                      >{{ item2.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" prop="lavel">
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-edit"
              @click="showEditDialog(scope.row.id)"
              >编辑</el-button
            >

            <el-button
              type="warning"
              size="mini"
              icon="el-icon-delete"
              @click="RemoveById(scope.row.id)"
              >删除</el-button
            >
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-setting"
              @click="showSetRightDialog(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加角色 -->
    <el-dialog
      title="添加角色"
      :visible.sync="addDialogVisible"
      width="30%"
      @close="addFormClose"
    >
      <el-form
        label-width="80px"
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRolesInfo">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑角色 -->
    <el-dialog
      title="编辑角色"
      :visible.sync="shoEditDialogVisible"
      width="30%"
    >
      <el-form label-width="80px" :model="editForm" ref="editFormRef">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="shoEditDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveEditInfo">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配权限的对话款 -->
    <el-dialog title="分配权限" :visible.sync="setRightDialog" width="50%">
      <el-tree
        :data="rightsList"
        :props="treeProps"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="defaultKeys"
        ref="treeRef"
      >
      </el-tree>

      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialog = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    const checkRolesName = (rule, value, callback) => {
      const regRolesName = /^(?:[\u4e00-\u9fa5·]{2,5})$/

      if (regRolesName.test(value)) return callback()

      callback(new Error('请输入正确的角色名称(中文)'))
    }
    return {
      rolesList: [],
      addDialogVisible: false,
      addForm: {
        roleName: '',
        roleDesc: ''
      },
      addFormRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 2, max: 5, message: '角色长度在2~5位之间!', trigger: 'blur' },
          { validator: checkRolesName, trigger: 'blur' }
        ]
      },
      shoEditDialogVisible: false,
      editForm: {},
      // 控制分配权限对话的显示与隐藏
      setRightDialog: false,
      // 所有权限的数据
      rightsList: [],
      // 树形控件
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      defaultKeys: [],
      // 当前即将分配权限的角色id
      roleId: ''
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败！')
      }

      this.rolesList = res.data
      console.log(this.rolesList)
    },
    showAddRolesDialog() {
      this.addDialogVisible = true
    },
    async saveRolesInfo() {
      const { data: res } = await this.$http.post('roles', this.addForm)
      if (res.meta.status !== 201) return this.$message.error('添加用户失败!')

      this.$message.success('添加用户成功!')
      this.getRolesList()
      this.addDialogVisible = true
    },
    addFormClose() {
      this.$refs.addFormRef.resetFields()
    },
    async showEditDialog(id) {
      const { data: res } = await this.$http.get('roles/' + id, this.addForm)
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色信息失败！')
      }

      this.editForm = res.data
      this.shoEditDialogVisible = true
    },
    saveEditInfo() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return false
        const { data: res } = await this.$http.put(
          'roles/' + this.editForm.roleId,
          {
            roleName: this.editForm.roleName,
            roleDesc: this.editForm.roleDesc
          }
        )
        if (res.meta.status !== 200) {
          return this.$message.error('修改角色数据失败！')
        }
        this.getRolesList()
        this.shoEditDialogVisible = false
      })
    },
    async RemoveById(id) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该角色, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch((err) => err)

      if (confirmResult !== 'confirm') return this.$message.info('已取消删除')

      const { data: res } = await this.$http.delete('roles/' + id)
      if (res.meta.status !== 200) return this.$message.error('删除角色失败！')

      this.$message.success('删除角色成功！')
      this.getRolesList()
    },
    async removeId(role, rightsId) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该权限, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
      if (confirmResult !== 'confirm') return this.$message.info('已取消删除！')
      const { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${rightsId}`
      )
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('删除角色权限失败！')
      }

      this.$message.success('删除角色权限成功！')
      // this.getRolesList()
      // 防止权限删除折叠面板
      role.children = res.data
    },
    // 展示分配权限的对话款
    async showSetRightDialog(role) {
      this.roleId = role.id
      // 获取所有权限的数据
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) {
        return this.$message.error('获取权限数据失败！')
      }

      // 把获取的权限数据保存到data中
      this.rightsList = res.data
      // 递归获取三级节点的id
      this.getLeafKeys(role, this.defaultKeys)
      this.setRightDialog = true
    },

    // 通过递归的形式，获取角色下所有三级权限的id，并保存到dqfKeys数组中
    getLeafKeys(node, arr) {
      // 如果当前node节点不包含children属性，则是三级节点
      if (!node.children) {
        return arr.push(node.id)
      }

      node.children.forEach((item) => this.getLeafKeys(item, arr))
    },
    // 为角色分配权限
    async allotRights() {
      // getCheckedKeys -- 则返回目前被选中的节点的 key 所组成的数组
      // getHalfCheckedKeys -- 则返回目前半选中的节点的 key 所组成的数组
      // 将所有选中的节点 key 值合并
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      console.log(keys)

      const idStr = keys.join(',')

      const { data: res } = await this.$http.post(
        `roles/${this.roleId}/rights`,
        { rids: idStr }
      )

      if (res.meta.status !== 200) return this.$message.error('分配权限失败！')

      this.$message.success('分配权限成功！')

      this.getRolesList()

      this.setRightDialog = false
    }
  }
}
</script>
<style lang="less" scoped>
.el-col {
  text-align: center;
  margin: 5px 0;
}
.el-tag {
  margin: 0 5px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>
